<template>
  <el-card class="box-card" style="width: 100%; max-width: 800px; margin: 0 auto; height: 600px">
    <h2>{{ title }}</h2>
    <el-form
        :model="form"
        :rules="rules"
        ref="formRef"
        label-width="120px"
        class="form-container"
    >
      <el-form-item label="姓名：" prop="username">
        <el-input v-model="form.username" class="input-field" />
      </el-form-item>

      <el-form-item label="部门：" prop="department">
        <el-input v-model="form.department" class="input-field" />
      </el-form-item>

      <el-form-item label="角色：" prop="role">
        <el-select v-model="form.role" placeholder="请选择角色" class="input-field">
          <el-option
              v-for="opt in roleOptions"
              :key="opt.id"
              :label="opt.roleName"
              :value="opt.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="昵称（选填）：">
        <el-input v-model="form.nickname" class="input-field" />
      </el-form-item>

      <el-form-item label="电话：" prop="phone">
        <el-input v-model="form.phone" class="input-field" />
      </el-form-item>

      <el-form-item label="密码：" prop="password">
        <el-input type="password" v-model="form.password" class="input-field" />
      </el-form-item>

      <el-form-item>
        <div class="button-container">
          <el-button type="primary" @click="onSubmit">保存</el-button>
          <el-button @click="onCancel">取消</el-button>
        </div>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script setup>
import { onMounted, ref } from 'vue';
import { useRoute } from 'vue-router';
import axios from 'axios';
import { ElMessage, ElMessageBox } from 'element-plus';
import { router } from '@/router/index.js';

const route = useRoute();

const title = ref('用户信息');
const form = ref({});
const roleOptions = ref([]);
const formRef = ref(null);

const rules = {
  username: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  department: [{ required: true, message: '请输入部门', trigger: 'blur' }],
  role: [{ required: true, message: '请选择角色', trigger: 'change' }],
  phone: [
    { required: true, message: '请输入电话', trigger: 'blur' },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: '请输入有效的手机号',
      trigger: 'blur',
    },
  ],
  password: [
    {
      required: route.params.id < 0,
      message: '请输入密码',
      trigger: 'blur',
    },
    {
      min: 6,

      message: '密码必须为6位',
      trigger: 'blur',
    },
  ],
};

const onSubmit = () => {
  formRef.value.validate((valid) => {
    if (!valid) return;

    ElMessageBox.confirm('确定保存表单吗？', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
        .then(() => {
          if (route.params.id < 0) {
            axios.post(`/user/addAccount`, form.value).then((resp) => {
              if (resp.data) {
                ElMessage.success('添加账号成功');
              } else {
                ElMessage.error('添加账号失败');
              }
              router.push('/accountList');
            });
          } else {
            axios
                .post(`/user/saveChangeUser/${route.params.id}`, form.value)
                .then((resp) => {
                  if (resp.data) {
                    ElMessage.success('保存成功');
                  } else {
                    ElMessage.error('保存失败');
                  }
                  router.push('/accountList');
                })
                .catch(() => {
                  ElMessage.error('请求失败，请稍后重试');
                });
          }
        })
        .catch(() => {
          ElMessage.info('已取消保存');
        });
  });
};

const onCancel = () => {
  ElMessageBox.confirm('确定退出页面吗？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
      .then(() => {
        router.push('/accountList');
      })
      .catch(() => {
        ElMessage.info('已取消');
      });
};

const getAccount4Edit = () => {
  axios.post(`/user/getAccount4Edit/${route.params.id}`).then((resp) => {
    const data = resp.data;

    // 修复：将字符串角色名称转换成对应的角色 ID
    const matchedRole = roleOptions.value.find(role => role.roleName === data.role);
    data.role = matchedRole ? matchedRole.id : null;

    form.value = data;
  });
};

const getAllRole4Select = () => {
  axios.get('/user/getAllRoles').then((resp) => {
    roleOptions.value = resp.data;
  });
};

onMounted(() => {
  getAllRole4Select();
  if (route.params.id >= 0) getAccount4Edit();
});
</script>

<style scoped>
.box-card {
  width: 100%;
  max-width: 600px;
  margin: 0 auto;
}

.form-container {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.input-field {
  width: 70%;
}

.el-form-item {
  width: 100%;
  margin-bottom: 16px;
  text-align: left;
}

.button-container {
  display: flex;
  justify-content: center;
  gap: 10px;
}
</style>
